#encoding=utf-8

from ctypes import *
import serial
import serial.tools.list_ports
import os
import sys
import binascii
from datetime import date
from hexdump2 import hexdump

print("欢迎使用 ymodem 升级工具, 默认配置1K-modem, com baudrate = 115200 \r")

# Step1:  检查目标文件夹下的app.bin 文件是否存在

path = sys.path[0]
file_path = path + "\\file\\app.bin"
print(file_path)

file = open(file_path, 'rb')
file_size = os.path.getsize(file_path) #获得文件大小

#print("bin文件大小为:\r" %(file_size))
print('bin file size = %s' % (file_size))

# bin 文件打印出来用于调试
#buff = file.read(file_size)
#print("bin文件内容为:\r")
#hexdump(buff)

file.close()

# Step2:  操作串口

# 遍历当前PC上所有的串口设备
port_list = list(serial.tools.list_ports.comports())
if len(port_list) == 0:
    print("[ERR]无可用的串口!!!")
else:
    for i in range(0, len(port_list)):
        print(port_list[i])

comx = input("(例如:COM1,只需输入1,回车即可)\r\n" + "请输入串口号:")

port = int(comx)

dll = CDLL(".\\lib2\\PCOMM.dll")

y = dll.sio_open(port)    #打开串口
x = dll.sio_ioctl(port, 16, 0x00 | 0x03 | 0x00) # 115200, 无校验，8位数据位，1位停止位
#print(x)
#print(y)

def callback_fun(Zmitlen, buflen, pbuf, flen):
    print (Zmitlen, flen)
    return 0
CALLBACK = WINFUNCTYPE(c_int, c_long, c_int, POINTER(c_char), c_long)
ccb = CALLBACK(callback_fun)

source = br'.\\file\\app.bin'
ret = dll.sio_FtYmodemTx(port, source, ccb, 27)
print(ret)

dll.sio_close(port)


#raw_input("Press <enter>")
# 打包命令 pyinstaller -F main.py

